define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');

    var version = require('../../../c/template/index');

    var template = {
        init: function () {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "技术服务费模板管理") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            this.initCity();
            this.initValidator();
            this.bindEvent();
        },
        /**
         * 表单验证初始化
         */
        initValidator: function () {
            $('#J_Search').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                }
            });
        },
        /**
         * 城市初始化
         */
        initCity: function () {
            var self = this;
            CRM.request({
                "type": 'POST',
                "url": CRM.getOuterUrl('/shop/city/queryOpenCity'),
                "dataType": "json",
                contentType: "application/json",
                data: JSON.stringify({}),
                "success": function (req) {
                    if (req.status) {
                        $.each(req.entry, function (_index, _city) {
                            $("#city").append("<option value='" + _city.cityCode + "'>" + _city.city + "</option>");
                        });
                        self.queryUsingTemplate();
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 查询在用的模板
         */
        queryUsingTemplate:function(){
            var self = this;
            $("#info_1").html('<button type="button" id="new_1" class="btn btn-danger" data-id="1">新增模板</button>')//清空
            $("#info_2").html('<button type="button" id="new_2" class="btn btn-danger" data-id="2">新增模板</button>')//清空
            $("#info_3").html('<button type="button" id="new_3" class="btn btn-danger" data-id="3">新增模板</button>')//清空
            CRM.request({
                "type": 'get',
                "url": CRM.getOuterUrl('/centralbank/commission/queryUsingTemplate'),
                "dataType": "json",
                contentType: "application/x-www-form-urlencoded",
                data: {
                    cityCode:$("#city").val()
                },
                "success": function (req) {
                    if (req.status) {
                        $.each(req.entry.versionMap, function (_index, _versions) {
                            var _data = {};
                            _data.versionList = [];
                            $.each(_versions, function (_length, _version) {
                                _data.versionList.push({
                                    id:_index + "_" + _version,
                                    version:_version
                                })
                            });
                            $.each(req.entry.nowVersionMap, function (_length, _version) {
                                if(_length == _index){//判断当前有效的版本
                                    _data.nowVersion = _version;
                                }
                            });
                            $.each(req.entry.bankCommissionTemplateMap, function (_length, _template) {
                                if(_length == _index){//判断当前的模板
                                    $.each(_template.commissionRuleMap, function (_key, _commissionRuleMap) {
                                        var key  = _key.split("@");
                                        _template.commissionRuleMap[_key] = {};
                                        _template.commissionRuleMap[_key].id = key[0];
                                        _template.commissionRuleMap[_key].name = key[1];
                                        _template.commissionRuleMap[_key].list = _commissionRuleMap;
                                    });
                                    _data.template = _template;
                                }
                            });
                            $("#info_" + _index).html(version.build(_data));
                        });
                        self.initDatetimepicker();
                        self.bindTabEvent();
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 保存数据
         * @param e
         */
        updateTemplate:function(e){
            var id = $(e.target).attr("data-id");
            var ids = id.split("_");
            var _data = {};
            _data.rateMap = {};
            $($("#" + id + "_form").serializeArray()).each(function () {//获取查询条件
                if(this.name == "startDate"){
                    _data.startDate = this.value;
                }else if(this.name == "basePriceFee") {
                    _data.baseFee = this.value * 100;
                }else{
                    _data.rateMap[this.name] = this.value * 100;
                }
            });
            _data.city = $("#city").find("option:selected").text();
            _data.type = ids[0];
            _data.version = ids[1];
            CRM.request({
                "type": 'POST',
                "url": CRM.getOuterUrl('/centralbank/commission/updateTemplate'),
                "dataType": "json",
                data: JSON.stringify(_data),
                "success": function (req) {
                    if (req.status) {
                        CRM.showDialog(req.message);
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 以当前模板新增模板
         * @param e
         */
        addTemplate:function(e){
            var self = this;
            var id = $(e.target).attr("data-id");
            var ids = id.split("_");
            var _data = {};
            _data.rateMap = {};
            $($("#" + id + "_form").serializeArray()).each(function () {//获取查询条件
                if(this.name == "startDate"){
                    _data.startDate = this.value;
                }else if(this.name == "basePriceFee") {
                    _data.baseFee = this.value * 100;
                }else{
                    _data.rateMap[this.name] = this.value * 100;
                }
            });
            _data.city = $("#city").find("option:selected").text();
            _data.type = ids[0];
            _data.version = ids[1];
            CRM.request({
                "type": 'POST',
                "url": CRM.getOuterUrl('/centralbank/commission/addTemplate'),
                "dataType": "json",
                data: JSON.stringify(_data),
                "success": function (req) {
                    if (req.status) {
                        CRM.showDialog(req.message);
                        self.queryUsingTemplate();
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 新建模板
         * @param e
         */
        newTemplate:function(e){
            var self = this;
            var type = $(e.target).attr("data-id");
            var _data = {};
            _data.rateMap = {};
            CRM.request({
                "type": 'get',
                "url": CRM.getOuterUrl('/centralbank/commission/queryTemplate'),
                "dataType": "json",
                contentType: "application/x-www-form-urlencoded",
                data: {
                    cityCode:$("#city").val(),
                    type:type
                },
                "success": function (req) {
                    if (req.status) {
                        var _data = {};
                        _data.versionList = [];
                        _data.versionList.push({
                            id:type + "_" + 1,
                            version:1
                        });
                        _data.nowVersion = 1;
                        $.each(req.entry.commissionRuleMap, function (_key, _commissionRuleMap) {
                            var key  = _key.split("@");
                            req.entry.commissionRuleMap[_key] = {};
                            req.entry.commissionRuleMap[_key].id = key[0];
                            req.entry.commissionRuleMap[_key].name = key[1];
                            req.entry.commissionRuleMap[_key].list = _commissionRuleMap;
                        });
                        _data.template = req.entry;
                        console.log(_data)
                        console.log(version.build(_data))
                        $("#info_" + type).html(version.build(_data));
                        self.initDatetimepicker();
                        self.bindTabEvent();
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 初始化日期控件
         */
        initDatetimepicker: function () {
            $(".form_time").datetimepicker({
                language: 'zh-CN',
                weekStart: 1,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 1,
                minView: 0,
                maxView: 1,
                forceParse: 0
            });
            $('.form_date').datetimepicker({
                language: 'zh-CN',
                weekStart: 1,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                minView: 2,
                forceParse: 0
            });
        },
        bindEvent: function () {
            var self = this;
            $(document).on('change', '#city', function () {
                self.queryUsingTemplate();
            });
        },
        /**
         * 绑定tab事件
         */
        bindTabEvent: function () {
            var self = this;
            $('button[id^="save_"]').unbind('click');
            $('button[id^="save_"]').on('click',function(e){
                self.updateTemplate(e)
            });
            $('button[id^="add_"]').unbind('click');
            $('button[id^="add_"]').on('click',function(e){
                self.addTemplate(e)
            });
            $('button[id^="new_"]').unbind('click');
            $('button[id^="new_"]').on('click',function(e){
                self.newTemplate(e)
            });
            $('a[user-target="tab_main"]').unbind('shown.bs.tab');
            $('a[user-target="tab_main"]').on('shown.bs.tab', function (e) {
                var ids = $(e.target).attr("aria-controls");
                var id = ids.split("_");
                if($("#" + ids).children().length == 0){
                    CRM.request({
                        "type": 'get',
                        "url": CRM.getOuterUrl('/centralbank/commission/queryTemplate'),
                        "dataType": "json",
                        contentType: "application/x-www-form-urlencoded",
                        data: {
                            cityCode:$("#city").val(),
                            type:id[0],
                            version:id[1]
                        },
                        "success": function (req) {
                            if (req.status) {
                                var _data = {};
                                $.each(req.entry.commissionRuleMap, function (_key, _commissionRuleMap) {
                                    var key  = _key.split("@");
                                    req.entry.commissionRuleMap[_key] = {};
                                    req.entry.commissionRuleMap[_key].id = key[0];
                                    req.entry.commissionRuleMap[_key].name = key[1];
                                    req.entry.commissionRuleMap[_key].list = _commissionRuleMap;
                                });
                                _data.template = req.entry;
                                _data.id = ids;
                                $("#" + ids).html(version.buildRule(_data))
                                self.initDatetimepicker();
                                self.bindTabEvent();
                            } else {
                                CRM.showDialog(req.message);
                            }
                        }
                    });
                }
            })
        }
    };
    template.init();
});